package com.huang.gateway.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.huang.gateway.constant.GatewayConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;


/**
 * @author hqy
 * @date 2022年06月20日 12:08
 */
@Component
public class GatewayGlobalFilter implements GlobalFilter, Ordered {

    @Autowired
    private StringRedisTemplate redisTemplate;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        String path = request.getURI().getPath();
        if(GatewayConstant.ALLOW_URIS.contains(path)){
            return chain.filter(exchange);
        }else{
            //从请求头里面获取token
            String authorization = request.getHeaders().getFirst("Authorization");

            if(StringUtils.hasText(authorization)){
                String token = authorization.replaceFirst("bearer ","");
                if(redisTemplate.hasKey(GatewayConstant.TOKEN_PREFIX + token)){
                    return chain.filter(exchange);
                }
            }
        }

        HashMap<String,Object> map = new HashMap<>();
        map.put("code", HttpStatus.UNAUTHORIZED);
        map.put("msg","没有登录，，您当前还没有权限对该资源进行访问哦！！！！");
        DataBufferFactory dataBufferFactory = response.bufferFactory();
        DataBuffer wrap = null;
        try {
            wrap = dataBufferFactory.wrap(new ObjectMapper().writeValueAsBytes(map));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return response.writeWith(Mono.just(wrap));
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
